package com.herench.bunch.clinic.convert;

import ca.uhn.hl7v2.model.GenericComposite;
import ca.uhn.hl7v2.model.GenericPrimitive;
import ca.uhn.hl7v2.model.Message;
import ca.uhn.hl7v2.model.Varies;
import ca.uhn.hl7v2.model.v24.datatype.CE;
import ca.uhn.hl7v2.model.v24.group.RTB_K13_ROW_DEFINITION;
import ca.uhn.hl7v2.model.v24.message.QBP_Q11;
import ca.uhn.hl7v2.model.v24.message.RTB_K13;
import ca.uhn.hl7v2.model.v24.segment.MSA;
import ca.uhn.hl7v2.model.v24.segment.MSH;
import ca.uhn.hl7v2.model.v24.segment.QPD;
import ca.uhn.hl7v2.model.v24.segment.RDT;
import ca.uhn.hl7v2.parser.DefaultModelClassFactory;
import com.herench.bunch.clinic.handler.ProxyMsgCodeConstant;
import com.herench.bunch.clinic.support.ProxyMsgTemplate;
import com.herench.bunch.commons.utils.MessageHelper;
import com.herench.bunch.commons.support.RequestMessage;
import org.dom4j.Document;
import org.dom4j.Element;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import java.util.Iterator;


public class DeptClinicAppointConvert extends AbstractMessageConvert {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public Document doToMessage(RequestMessage requestMessage) throws Exception {
        Document document = ProxyMsgTemplate.getInMsgAppoint(ProxyMsgCodeConstant.DEPT_OF_APPONIT);
        Element DataRow = document.getRootElement().element("CommitData").addElement("DataNode1").addElement("DataRow");
        QBP_Q11 hl7 = (QBP_Q11) requestMessage.getHl7Message();
        GenericComposite gc = (GenericComposite) hl7.getQPD().getQpd3_UserParametersInsuccessivefields().getData();
        if (gc != null) {
            Varies varies = (Varies) gc.getComponent(1);
            if (varies != null) {
                GenericPrimitive primitive = (GenericPrimitive) varies.getData();
                String qpdString = primitive.getValue();
                String[] qpds = qpdString.split("#");
                if (qpds.length < 2) {
                    throw new RuntimeException("缺少必要参数");
                }
//                DataRow.addAttribute(qpds[0].split("=")[0],qpds[0].split("=")[1] != null ? qpds[0].split("=")[1] : "");
//                DataRow.addAttribute(qpds[0].split("=")[0],qpds[0].split("=")[1] != null ? qpds[0].split("=")[1] : "");
//                DataRow.addAttribute(qpds[0].split("=")[0],qpds[0].split("=")[1] != null ? qpds[0].split("=")[1] : "");
//                DataRow.addAttribute(qpds[0].split("=")[0],qpds[0].split("=")[1] != null ? qpds[0].split("=")[1] : "");

                for (String qpd : qpds) {
                    String[] temp = qpd.split("=");
                    if (temp.length > 1) {
                        DataRow.addAttribute(temp[0], temp[1] != null ? temp[1] : "");
                    } else {
                        DataRow.addAttribute(temp[0], "");
                    }
                }
            }
        }
        String res = document.asXML();
        logger.info(requestMessage.getMsgCode() + " to HIS XML = " + res);
        return document;
    }

    @Override
    public Message doFromMessage(String message) throws Exception {
        Assert.notNull(message, "message 为空");
        Document doc = ProxyMsgTemplate.getOutMsgTpl(message);
        RTB_K13 rtbK13 = new RTB_K13();
        rtbK13.initQuickstart("RTB_K13", "RTB_K13", "P");
        MSH msh = rtbK13.getMSH();
        initResponseMessageMSH(msh);

        MSA msa = rtbK13.getMSA();
        String res = doc.getRootElement().element("Result").element("Info").attributeValue("EXECUTE_FLAG");
        if ("0".equals(res)){
            res = "1";
        }
        msa.getErrorCondition().getCe1_Identifier().setValue(res);
        msa.getErrorCondition().getCe2_Text().setValue(doc.getRootElement().element("Result").element("Info").attributeValue("EXECUTE_MESSAGE"));


        RTB_K13_ROW_DEFINITION definition = rtbK13.getROW_DEFINITION();

        Element DataNode1 = doc.getRootElement().element("ReturnData").element("DataNode1");
        if (DataNode1 == null) {
            msa.getErrorCondition().getCe2_Text().setValue("无数据");
        } else {
            int index = 0;
            for (Iterator<Element> iterator = DataNode1.elementIterator(); iterator.hasNext(); ) {
                Element el = iterator.next();
                RDT rdt = new RDT(rtbK13, new DefaultModelClassFactory());
                CE ce = new CE(rtbK13);
                ce.getCe1_Identifier().setValue("RD");
                StringBuffer buffer = new StringBuffer();
                buffer.append("ClinicDate=").append(el.attributeValue("CLINIC_DATE")).append("#")
                        .append("TimeDesc=").append(el.attributeValue("TIME_DESC")).append("#")
                        .append("ClinicType=").append(el.attributeValue("CLINIC_TYPE")).append("#")
//                        .append("AppointmentLimits=").append(el.attributeValue("APPOINTMENT_LIMITS")).append("#")
                        .append("AppointmentLimits=").append(el.attributeValue("NUM_CAN_BE_REGISTED")).append("#")
                        .append("AppointmentNum=").append(el.attributeValue("APPOINTMENT_NUM")).append("#")
                        .append("RegistFee=").append(el.attributeValue("REGIST_FEE")).append("#")
                        .append("ClinicFee=").append(el.attributeValue("CLINIC_FEE")).append("#")
                        .append("OtherFee=").append(el.attributeValue("OTHER_FEE")).append("#")
                        .append("ClinicDept=").append(el.attributeValue("CLINIC_DEPT")).append("#")
                        .append("DeptName=").append(el.attributeValue("DEPT_NAME")).append("#")
                        .append("DoctorCode=").append(el.attributeValue("DOCTOR_CODE")).append("#")
                        .append("Doctor=").append(el.attributeValue("DOCTOR")).append("#")
                        .append("OrderNo=").append("").append("#")
                        .append("HourStart=").append(el.attributeValue("HOUR_START")).append("#")
                        .append("HourEnd=").append(el.attributeValue("HOUR_END"));

                ce.getCe2_Text().setValue(buffer.toString());
                rdt.getColumnValue().setData(ce);
                definition.insertRDT(rdt, index++);
            }
        }
        return rtbK13;
    }


    @Override
    public Message generatorReqMessage() throws Exception {
        QBP_Q11 qbp = new QBP_Q11();
        qbp.initQuickstart("QBP_Q11", "QBP_Q11", "P");
        MSH msh = qbp.getMSH();
        msh.getMsh3_SendingApplication().getHd1_NamespaceID().setValue("SSM");
        msh.getMsh11_ProcessingID().getPt1_ProcessingID().setValue("200020");
        QPD qpd = qbp.getQPD();
        qpd.getMessageQueryName().getIdentifier().setValue("查询预约排班（S004）");
        qpd.getQpd2_QueryTag().setValue("QR");
        CE ce = new CE(qbp);
        ce.getCe1_Identifier().setValue("params");
        ce.getCe2_Text().setValue("CLINIC_VISIT_DATE=2019-08-26#TIME_DESC=上午#REGIST_FEE=10.00#CLINIC_FEE=0.00#OTHER_FEE=0.00#CLINIC_CHARGE=10.00#FEE_TYPE=0#HOUR_START=10:00#HOUR_END=11:00#REGIST_DETAIL_ID=#PATIENT_NAME=陈统#SEX=男#CHARGE_TYPE=#DATE_OF_BIRTH=1995-07-02#INSURANCE_NO=#ID_NO=331081199507027314#PHONE_NUMBER=13820026018#CREDENTIALS_NO=331081199507027314#CREDENTIALS_TYPE=1#PATIENT_ID=40021810311243270555#DEPT_CODE=01010201#DOCTOR_CODE=100000002");
        qpd.getUserParametersInsuccessivefields().setData(ce);
        System.out.println(MessageHelper.encode(qbp));
        return qbp;
    }
}
